package com.example.mqspring.rabiitmqbasicleverone.rabbitmqRPC;


import com.rabbitmq.client.*;
import com.rabbitmq.client.DefaultConsumer;

import java.io.IOException;

/**
 * 接收消息并回复消息
 */
public class RPCService extends DefaultConsumer {


    /**
     * @param channel the channel to which this consumer is attached
     */
    public RPCService(Channel channel) {
        super(channel);
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

//      回复给RPC请求端消息
        String reply = "OK ,i receive you message!";

        AMQP.BasicProperties basicProperties = new AMQP.BasicProperties();
//       根据生产者的correlationId 来构建对应的回应属性对象
        AMQP.BasicProperties replyProperties = basicProperties.builder().correlationId(properties.getCorrelationId()).build();
//      消费消息后应答消息,根据getReplyTo 确定回应对象
        getChannel().basicPublish("",properties.getReplyTo(),replyProperties,reply.getBytes());
//      发送ACK消息 如果开启的应答,那么这一步是给rabbitmq发送ack那边接收到才会消费的消息才会在队列中移除
//        如果不发,那么队列消息一直存在
//        deliveryTag 這个参数的值是中间件服务指派给特定消息的
//        deliver.getEnvelope().getDeliveryTag().可以获取这个值
//        multiple参数为false,对服务器的应答就是getDeliveryTag()的参数值所绑定的消息,否则就是应答所以消息直到最后一个
//        basicAck(0,true) 所以不应答的消息都会应答
        getChannel().basicAck(envelope.getDeliveryTag(), false);

        System.out.println("我是服务端接收到:"+new String(body));
    }
}
